import { _decorator, BoxCollider2D, Component, director, ERigidBody2DType, instantiate, Node, Prefab, RigidBody2D, TiledMap, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('MapManager')
export class MapManager extends Component {
    @property(Prefab)
    player: Prefab = null;
    @property(Node)
    playerNode: Node = null;
    @property(TiledMap)
    tiledMap: TiledMap = null;
    start() {
        let player = instantiate(this.player);
        this.playerNode.addChild(player);
        this.initGround();
        this.initHouse();
    }
    initGround(){
        let tiledSize = this.tiledMap.getTileSize();
        let layer = this.tiledMap.getLayer("地面");
        let layerSize = layer.getLayerSize();
        for (let i = 0; i < layerSize.width; i++) {
            for (let j = 0; j < layerSize.height; j++) {
                let gid = layer.getTileGIDAt(i,j)
                if (gid != 0) {
                    let tiled = layer.getTiledTileAt(i,j, true);
                    let rigid = tiled.node.addComponent(RigidBody2D);
                    let collider = tiled.node.addComponent(BoxCollider2D);
                    collider.offset = new Vec2(tiledSize.width / 2, tiledSize.height / 2);
                    // rigid.bullet = true;
                    rigid.type = ERigidBody2DType.Static
                    collider.size = tiledSize;
                    collider.apply();
                }

            }
        }
    }
    initHouse(){
        let tiledSize = this.tiledMap.getTileSize();
        let layer = this.tiledMap.getLayer("房屋");
        let layerSize = layer.getLayerSize();
        for (let i = 0; i < layerSize.width; i++) {
            for (let j = 0; j < layerSize.height; j++) {
                let gid = layer.getTileGIDAt(i,j)
                if (gid != 0) {
                    let tiled = layer.getTiledTileAt(i,j, true);
                    let rigid = tiled.node.addComponent(RigidBody2D);
                    let collider = tiled.node.addComponent(BoxCollider2D);
                    collider.offset = new Vec2(tiledSize.width / 2, tiledSize.height / 2);
                    rigid.type = ERigidBody2DType.Static
                    // rigid.bullet = true;
                    collider.size = tiledSize;
                    collider.apply();
                }

            }
        }
    }
    update(deltaTime: number) {

    }
}

